# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   File Name：     RedisClient
   Description :  aes 对称加密
   Author :        William
   date：          2020.2.19
-------------------------------------------------
   Change Activity:
                   2020.2.19: aes 对称加密
-------------------------------------------------
"""
__author__ = 'William'

from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
from Config.Setting import KEY_STR,IV_B


class AES_:
    def __init__(self,key_str,iv_b):
        #先进行字符串16位补全，然后转化位btype类型
        self.key = key_str.ljust(16,'\0').encode('utf-8')
        self.iv_b = (iv_b.ljust(16,'\0')).encode('utf-8')
        self.mode = AES.MODE_CBC

    # 如果text不足16位的倍数就用0补足为16位
    def add_to_16(self,text):
        return str(text).ljust(16,"\0").encode('utf-8')

    # 加密函数
    def encrypt(self,text):
        text = self.add_to_16(text)
        cryptos = AES.new(self.key, self.mode, self.iv_b)
        cipher_text = cryptos.encrypt(text)
        # 因为AES加密后的字符串不一定是ascii字符集的，输出保存可能存在问题，所以这里转为16进制字符串
        return b2a_hex(cipher_text)

    # 解密后，去掉补足的空格用strip() 去掉
    def decrypt(self,text):
        cryptos = AES.new(self.key, self.mode, self.iv_b)
        plain_text = cryptos.decrypt(a2b_hex(text))
        return bytes.decode(plain_text).rstrip('\0')

aes = AES_(KEY_STR,IV_B)

if __name__ == '__main__':
    e = aes.encrypt("hello world")  # 加密
    d = aes.decrypt(e)  # 解密
    print("加密:", e)
    print("解密:", d)